<?php

namespace app\index\controller;

use app\index\model\Unionid;
use think\Controller;
use think\Log;
use think\Request;
use function fast\e;

class Wmini extends Controller
{

    public function subscribe(Request $request)
    {
        $data = $request->getContent();  // 获取微信服务器发送的原始XML数据
        $xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        $event = (string)$xml->Event;  // 事件类型
        $openid = (string)$xml->FromUserName;  // 用户的openid
        if ($event == 'subscribe') {
            // 用户关注事件
            $this->handleSubscribe($openid);
        }

        // 回复微信服务器"success"表示已接收处理
        echo 'success';
    }


    public function getUserAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx037190c68e79444d&secret=3ab7e4c9319f57b94f9ec66cc9c4cacf";
        $res = json_decode($this->curl_get($url),true);
        return $res['access_token'];

    }


    public function getUserInfoByToken($access_token,$open_id)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$open_id&lang=zh_CN";
        $res = json_decode($this->curl_get($url),true);
        if ($res['unionid']){
            return $res['unionid'];
        }

        return false;

    }



    function curl_get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);          //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);         //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }






    public function handleSubscribe($openid)
    {
        $access_token = $this->getUserAccessToken();
        $unionid  = $this->getUserInfoByToken($access_token,$openid);

        //添加数据
        if($unionid){
            //查询是否存在
            $unionids = (new Unionid())->where(['unionid' => $unionid])->find();
            if($unionids){
                (new Unionid())->where(['unionid' => $unionid])->update(['w_openid' => $openid]);
            }else{
                (new Unionid())->insert(['w_openid' => $openid,'unionid' => $unionid] );
            }
        }

    }




}